<template>
  <div class="app-container">
    <el-form :inline="true" :model="listQuery" @submit.native.prevent>
      <el-form-item label="商品名称">
        <el-input size="small" v-model="listQuery.q_name1" minlength="2" maxlength="20"></el-input>
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select
          class="toolbar-lable-right"
          size="small"
          v-model="listQuery.q_state1"
          placeholder="请选择"
        >
          <el-option
            v-for="item in optStateValues"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商家">
        <el-select
          class="toolbar-lable-right"
          size="small"
          v-model="listQuery.q_sellerId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in sellers"
            :key="item.id"
            :label="item.sellerName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="this.getList">查询</el-button>
        <el-button icon="el-icon-refresh-left" size="small" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="button-table-margin">
      <el-button size="small" type="primary" @click="viewDetails" v-permission="['admin/product/details']">商品详情</el-button>
      <el-button size="small" type="primary" @click="preview" v-permission="['admin/product/cate/auditPass']">预览</el-button>
      <el-button size="small" type="primary" @click="shelves" v-permission="['admin/product/auditProduct']">下架商品</el-button>
      <el-button size="small" type="primary" @click="deleteBtn" v-permission="['admin/product/auditProduct']">删除</el-button>
      <el-button size="small" type="primary" @click="setCommission" v-permission="['admin/sale/salescale/salescaleproduct']">设置佣金</el-button>
      <el-button size="small" type="primary" @click="setRecommend(1)">推荐</el-button>
      <el-button size="small" type="primary" @click="setRecommend(0)">取消推荐</el-button>
    </div>
    <el-table
      ref="singleTable"
      :data="dataList"
      v-loading="listLoading"
      border
      fit
      highlight-current-row
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleCurrentChange"
    >
      <el-table-column type="selection" align="center" width="50">
      </el-table-column>
      <el-table-column width="110" label="商品图片">
        <template slot-scope="scope">
          <img width="75" :src="$imagePath + scope.row.masterImg" alt="" />
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip width="350" property="name1" label="商品名称">
      </el-table-column>
      <el-table-column width="150" property="seller" label="商家">
      </el-table-column>
      <el-table-column property="productCateName" label="商品分类">
      </el-table-column>
      <el-table-column property="sellerCateName" label="店铺分类">
      </el-table-column>
      <el-table-column width="120" show-overflow-tooltip property="productBrandName" label="商品品牌">
      </el-table-column>
      <el-table-column show-overflow-tooltip width="120" property="productCode" label="商品编码">
      </el-table-column>
      <el-table-column property="costPrice" label="成本价"> </el-table-column>
      <el-table-column property="protectedPrice" label="保护价">
      </el-table-column>
      <el-table-column property="productStock" label="库存"> </el-table-column>
      <el-table-column property="actualSales" label="销量"> </el-table-column>
      <el-table-column label="是否推荐">
        <template slot-scope="scope">
          {{ codeBox.PRODUCT_IS_TOP[scope.row.isTop] }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ codeBox.PRODUCT_STATE[scope.row.state] }}
        </template>
      </el-table-column>
      <el-table-column width="160" property="upTime" label="上架时间">
      </el-table-column>
      <el-table-column width="160" property="createTime" label="创建时间">
      </el-table-column>
      <el-table-column property="saleScale1" label="一级分佣">
      </el-table-column>
      <el-table-column property="saleScale2" label="二级分佣">
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog title="设置佣金" :visible.sync="dialogFormVisible" width="40%">
      <el-form :model="commissionForm" :rules="rules" ref="commissionForm">
        <el-form-item label="商品名称" prop="name" :label-width="formLabelWidth">
          <div>{{ commissionForm.name }}</div>
        </el-form-item>
        <el-form-item label="一级分销" prop="opt_saleScale1" :label-width="formLabelWidth">
          <el-input v-model="commissionForm.opt_saleScale1" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="二级分销" prop="opt_saleScale2" :label-width="formLabelWidth">
          <el-input v-model="commissionForm.opt_saleScale2" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('commissionForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { waitSaleList, waitSaleSeller, saleAuditPass, setMission, isRecommond } from "@/api/product";
import { getCodeManager, codeToArray } from "@/api/all";
import Pagination from "@/components/Pagination";
import { Message } from "element-ui";
export default {
  name: "waitSale",
  components: { Pagination },
  data() {
    var validateCheckInput = (rule, value, callback) => {
      if (value > 1) {
        callback(new Error('只能输入0到1数字，并且小数点保留2位'));
      } else {
        callback();
      }
    };
    return {
      dataList: [],
      optStateValues: [],
      sellers: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        q_name1: "",
        q_state: "6",
        q_state1: "",
        q_sellerId: ""
      },
      currentRow: [],
      commissionForm: {
        opt_productId: '',
        name: '',
        opt_saleScale1: '',
        opt_saleScale2: ''
      },
      dialogFormVisible: false,  // 设置佣金
      formLabelWidth: '120px',
      rules: {
        name: [
          { required: true, message: '', trigger: 'blur' },
        ],
        opt_saleScale1: [
          { required: true, message: '请输入一级分销', trigger: 'blur' },
          { validator: validateCheckInput, trigger: 'blur' },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '只能输入0到1数字，并且小数点保留2位', trigger: 'blue' }
        ],
        opt_saleScale2: [
          { required: true, message: '请输入二级分销', trigger: 'blur' },
          { validator: validateCheckInput, trigger: 'blur' },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '只能输入0到1数字，并且小数点保留2位', trigger: 'blue' }
        ],
      }
    };
  },
  created() {
    // 商品状态
    getCodeManager("PRODUCT_STATE", () => {
      this.optStateValues = codeToArray("PRODUCT_STATE");
    });
    // 是否推荐
    getCodeManager("PRODUCT_IS_TOP", () => {});
    // 状态
    getCodeManager("PRODUCT_STATE", () => {});
    // 获取待售商品商家列表
    waitSaleSeller().then(res => {
      this.sellers = res.data.data.sellers;
    });
    this.getList();
  },
  methods: {
    handleCurrentChange(val) {
      // 选中当前行数据
      this.currentRow = val;
    },
    // 获取列表数据
    getList() {
      this.listLoading = true;
      waitSaleList(this.listQuery).then(res => {
        this.dataList = res.data.rows;
        this.total = res.data.total;
        this.listLoading = false;
        if(res.data.status == 500) {
          this.listLoading = false;
        }
      })
    },
    reset() {
      this.listQuery.q_name1 = "";
      this.listQuery.q_state1 = "";
      this.listQuery.q_sellerId = "";
      this.getList();
    },
    // 查看详情
    viewDetails() {
      if (this.currentRow.length != 1) {
        Message.error("查看详情，只能选择一条记录");
        return;
      }
      this.$router.push({
        path: "/product/productdetails",
        query: { productId: this.currentRow[0].id }
      });
    },
    // 预览
    preview() {
      if (this.currentRow.length != 1) {
        Message.error("预览，只能选择一条记录");
        return;
      }
      window.open(
        `${this.$frontUrl}/product/${this.currentRow[0].id}.html?preview=1`
      );
    },
    // 下架
    shelves() {
      if (this.currentRow.length == 0) {
        Message.error("请选择操作行。");
        return;
      }
      let ids = "";
      for (let i in this.currentRow) {
        if (this.currentRow.length > 1) {
          ids += this.currentRow[i].id + ",";
        } else {
          ids = this.currentRow[0].id;
        }
      }
      this.$confirm("确定要将商家的商品下架吗？", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        saleAuditPass({ type: 7, ids: ids }).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.getList();
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        });
      });
    },
    // 删除
    deleteBtn() {
      if (this.currentRow.length == 0) {
        Message.error("请选择操作行。");
        return;
      }
      let ids = "";
      for (let i in this.currentRow) {
        if (this.currentRow.length > 1) {
          ids += this.currentRow[i].id + ",";
        } else {
          ids = this.currentRow[0].id;
        }
      }
      this.$confirm("确定删除选中的商品吗？删除后,该商品将被强制下架", "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        saleAuditPass({ type: 5, ids: ids }).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.getList();
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        });
      });
    },
    // 设置佣金
    setCommission() {
      if (this.currentRow.length != 1) {
        Message.error("设置佣金请选择一条记录");
        return;
      }
      this.commissionForm.name = this.currentRow[0].name1
      this.commissionForm.opt_saleScale1 = this.currentRow[0].saleScale1
      this.commissionForm.opt_saleScale2 = this.currentRow[0].saleScale2
      this.commissionForm.opt_productId = this.currentRow[0].id
      this.dialogFormVisible = true;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          setMission(this.commissionForm).then(res => {
            if(!res.data.success) {
              Message.error(res.data.message);
              return;
            }
            Message.success('操作成功')
            this.dialogFormVisible = false;
            this.getList()
          })
        }
      });
    },
    // 是否推荐
    setRecommend(type) {
      if (this.currentRow.length == 0) {
        Message.error("请选择操作行。");
        return;
      }
      let [ids, top, message] = ["", 0, ''];
      // type为0代表不推荐，为1代表推荐
      if(type == 0) {
        top = 1;
        message = '确定要将商家的商品取消推荐吗？'
      } else {
        top = 2
        message = '确定要将商家的商品推荐吗？'
      }
      for (let i in this.currentRow) {
        if(top == 1) {
          if (this.currentRow[i].isTop == 1) {
            Message.error("选择商品中没有被推荐，请勿重复操作");
            return;
          }
        } else {
          if (this.currentRow[i].isTop == 2) {
            Message.error("选择商品中已经被推荐，请勿重复操作");
            return;
          }
        }
        if (this.currentRow.length > 1) {
          ids += this.currentRow[i].id + ",";
        } else {
          ids = this.currentRow[0].id;
        }
      }
      this.$confirm(message, "提示", {
        onfirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        isRecommond({ isTop: top, ids: ids }).then(res => {
          if (res.data.success) {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.getList();
          } else {
            this.$message({
              type: "error",
              message: res.data.message
            });
          }
        });
      });
    }
  }
};
</script>
<style scoped>
.filter-container .el-col-6 {
  margin-bottom: 15px;
}
.filter-item {
  margin-bottom: 0;
}
/deep/ .filter-container label {
  font-size: 14px;
  font-weight: 500;
  margin-right: 10px;
}
</style>
